from urllib import request
import requests
from aip import AipOcr
from bs4 import BeautifulSoup
from selenium import webdriver
from PIL import Image
from time import sleep
from urllib.parse import quote
from selenium.webdriver.common.keys import Keys
import configparser
import sys

driver = webdriver.Chrome()

userAccount = ""
passwd = ""
studyTimes = 0

def readConf():
    global userAccount
    global passwd
    global studyTimes

    try:
        cf = configparser.ConfigParser()
        cf.read("param.conf")
                    
        userAccount = cf.get("autostudy","userAccount").strip()
        passwd = cf.get("autostudy","passwd").strip()
        studyTimes = int(cf.get("autostudy","studyTimes").strip())
        if(studyTimes>0):
        	print(studyTimes)
    except BaseException:
        print("read config file faile,please retry")
        sys.exit(-1)
        
def get_yzm():  #自动处理验证码
    APP_ID = '10791852'
    API_KEY = 'xK9mmVIQNTHPURfd44DKpzBP'
    SECRET_KEY = 'U4i12gvyPXU76dpZhal9e9jzFMmKffv5'

    # 初始化AipFace对象
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    # 定义参数变量
    options = {
        'detect_direction': 'true',
        'language_type': 'CHN_ENG',
    }
    with open('yzm.png', 'rb') as fp:
        image = fp.read()
    res = client.basicGeneral(image, options)
    return res['words_result'][0]['words'].replace(" ","")

def get_yzm_img(yzm_element):
    location = yzm_element.location
    size = yzm_element.size
    rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))
    i = Image.open("yzm.png")
    bb = i.crop(rangle)
    bb.save("yzm.png","PNG")

def change_yzm():
    for link in driver.find_elements_by_xpath("//*[@href]"):
        if(link.get_attribute('href')=="javascript:bps.updateCheckCodeView()"):
            print("####change success\n")
            link.click()
            break
    sleep(0.5)

def save_yzm_img():
    try:
        driver.find_element_by_id('popwinConfirm').click()
        driver.refresh()
        init()
        change_yzm()
    except BaseException:
        print("not has confirm")
    driver.save_screenshot('yzm.png')
    yzm_element = driver.find_element_by_id('checkcode')
    get_yzm_img(yzm_element)

def login():
    y = driver.find_element_by_id('usercheckcode')
    y.clear()
    y.send_keys(get_yzm())
    driver.find_element_by_class_name('btn_denglu').click()

def init():
    driver.find_element_by_name('userAccount').clear()
    driver.find_element_by_name('userAccount').send_keys(userAccount) #"6500001170229"
    driver.find_element_by_name('userPassword').clear()
    driver.find_element_by_name('userPassword').send_keys(passwd) #"yt8888"

def test():
    #driver = webdriver.PhantomJS()
    save_yzm_img()
    login()
    try:
        sleep(1)
        print(driver.find_element_by_id('checkcode'))
        sleep(0.2)
        test()
    except BaseException:
        return True
    #driver.get('http://ssfw.xjnu.edu.cn/ssfw/report/cjgl/print/xsyxcj.do')
    #driver.save_screenshot("res.png")
    #driver.close()
    return True

def goto_my_study():
    flag = False
    for link in driver.find_elements_by_xpath("//*[@href]"):
        if(link.get_attribute('href')=="javascript:base.index2(1)"):
            link.click()
            flag = True
            break
    if(not flag):
        sleep(1)
        goto_my_study()
    sleep(0.1)

def study_course():
    #driver.switchTo().frame(driver.findElement(By.name("iframeWithElement")))
    #driver.find_element_by_id("bxCourse").click()
    flag = False
    for link in driver.find_elements_by_xpath("//*[@href]"):
        if(quote("中国共产党纪律处分条例", 'utf-8') in link.get_attribute('href')):
            print(link.get_attribute('href'))
            link.click()
            flag = True
            break 
    if(not flag):
        sleep(1)
        study_course()
    sleep(0.1)

def finlish_study():
    flag = False
    for link in driver.find_elements_by_xpath("//*[@href]"):
        if("exitStudy" in link.get_attribute('href')):
            link.click()
            flag = True
            break
    if(not flag):
        sleep(1)
        finlish_study()
    sleep(2)
    try:
        driver.find_element_by_id("popwinConfirm").click()
    except BaseException:
        sleep(1.5)
        finlish_study()


if __name__ == '__main__':
    url = "http://xf.faxuan.net"
    driver.get(url)
    driver.maximize_window()
    readConf()
    init()
    test()
    print(111)
    sleep(2.5)
    print(driver.title)
    goto_my_study()
    sleep(6)
    print(222)
    i = studyTimes
    while i>0:
        print("title:"+driver.title)
        study_course()
        driver.switch_to_window(driver.window_handles[1])
        print("title:"+driver.title)
        print(333)
        sleep(610)
        finlish_study()
        print(444)
        i = i-1
        sleep(2)
        driver.switch_to_window(driver.window_handles[0])
        #driver.save_screenshot("res.png")

